package com.attendcollatesys.excel.linstener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ListUtils;
import com.attendcollatesys.entity.ATDayDetails;
import com.attendcollatesys.entity.ATLeaveExtraDetail;
import com.attendcollatesys.entity.AtMonthTotalsPO;
import com.attendcollatesys.entity.excel.ExcelATDayDetails;
import com.attendcollatesys.ex.handler.ex.ExcelContentCheckException;
import com.attendcollatesys.service.ATLeaveExtraDetailService;
import com.attendcollatesys.service.AtMonthTotalsService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;

public class ExcelATMonthTotalsListener extends AnalysisEventListener<AtMonthTotalsPO> {

    /**
     * 每隔100条存储数据库
     */
    private static final int BATCH_COUNT = 100;

    private List<AtMonthTotalsPO> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private AtMonthTotalsService atMonthTotalsService;

    private StringBuilder sheetHeadValue=new StringBuilder();

    private int count;


    private boolean checkFlag = false;

    public ExcelATMonthTotalsListener(AtMonthTotalsService atMonthTotalsService) {
        this.atMonthTotalsService=atMonthTotalsService;
    }

    @Override
    public void invoke(AtMonthTotalsPO atMonthTotalsPO, AnalysisContext analysisContext) {
        //读取完表头就开始读取实际要录入的内容  此时需要校验的表头数据已全部拼装为一个字符串 这里再次压缩与先前压缩好的表头内容比对
        //项目为uft-8编码 选取其他编码格式 也会校验失败
//        if (!checkFlag) {
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//            try (GZIPOutputStream gzipOut = new GZIPOutputStream(baos)) {
//                gzipOut.write(sheetHeadValue.toString().getBytes());
//            } catch (Exception e) {
//                throw new RuntimeException("文件头检查失败");
//            }
//
//            String sheetHeadCode = "H4sIAAAAAAAAANWabWvaQADHv4rk1R4c9RKfX7cbvlgZnYwNCiNdXRFiMjJlHSI4BlPXiRvdKhuONptt6eg6B2Wy1NIv4536yq+wtNmsXuhlHOW8vNPo4e935u7/PzEvBIR4XtC1Zwl1ObUqxAN+4ZGm5DLq+fPs8ycpIS7cTS4k5m8JfkHNZZZS+j1ZyVmX1Zyi+IWnWT2trvy9JKBGGZo7/eJLuNZEP0uoeGSNWtI0JSWrE8OW5az87/FjTc/kFHl27JKmp1fSqqzMOz/wdORNa4ScPR9Q8AuALANGMnO37yQf/IeLfYkJu0hmF3lml8jsEs/sQTJ7kGf2EJk9xDN7mMwe5pk9QmaP8MweJbNHeWaPkdljPLMDl6QFAa7p3aKV62wFLuEKuE5X4BKvgOt8BS4BC7hOWOASsYDjjC3k8XYvXkK7h5smaux3Twz04seUej2uwfXeI5LZud55JDI71/tOkMzO9a4TIrOH6A7lbM/iYbKDl/o9zu6lfo+ze6nf4+ye6veOkPJUv3fQc52xeL930HOdsni/d9BznbN4v3fQc520eL930Huq30uX0e9/H1pdYUrNHhcANE1nqwRLr2B7u3vcQPVtViYi2USkMOntvusdGIlZVgoSWUGiuZt21+HbKiuBIFkgSCGwkLzfP9yBtTYrhxDZgar7V9Zh1YDNPfShNaX6j2uEqTWsJQ3N97BkwrWmtchR/RcrpQhZKUKzwjunGqjydfCRsUyULBOl+X7qbcth8OUzbG5MQylGVopRKPVPNmG5hep7g2IR7RsM1w9+nHAkI022T+iMfUMP7R/1FtUr4jX1KjNFt/CnSf8LFedWs7psGaIjQ4LNT9ZrIjtTl3IAaNoBfL3Vq31nu8Two4pDhKYj9A8M+88itsuiOuyUsS3ed8Nnb5Wjpy63MukdZ3eC77pvfAKHnQqzOXRpKYCmpozmsGuaVtCfzSE2rzPRYecNKn+DtQ2xe1yFrZq1nbH0dmk2gKbajHtbx5ZJb3suZrADwTRnofAH5eTvzXElAAA=";
//            if(!Base64.getEncoder().encodeToString(baos.toByteArray()).equals(sheetHeadCode)){
//                System.out.println(Base64.getEncoder().encodeToString(baos.toByteArray()));
//             //   throw new ExcelContentCheckException("月度考勤汇总表表头数据与预期不符");
//            }
//            checkFlag=!checkFlag;
//        }



        cachedDataList.add(atMonthTotalsPO);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 此方法会读取前表头内容
     */
//    @Override
//    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
//        ObjectMapper objectMapper = new ObjectMapper();
//        count++;
//        if(count==2)return;//导出人不用检验内容
//        try {
//            sheetHeadValue.append(objectMapper.writeValueAsString(headMap));
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException("文件头解析失败");
//        }
//
//    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (cachedDataList.size() > 0) {
            saveData();
        }
        System.out.println("月度考勤sheet导入完毕");
    }


    private void saveData(){
        ArrayList<AtMonthTotalsPO> atMonthTotalsPOArrayList = new ArrayList<>();
        ArrayList<String> daySerList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        for (int i = 0; i < cachedDataList.size(); i++) {
            cachedDataList.get(i).setSerialNo(sdf.format(cachedDataList.get(i).getAttendanceDate()) +
                    cachedDataList.get(i).getRtxNumber());
            daySerList.add(cachedDataList.get(i).getSerialNo());

        }



        atMonthTotalsService.deleteByserialNo(daySerList);
        atMonthTotalsService.insertBatch(cachedDataList);
    }
}
